package com.basker.pisces.oss.facade.web;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.basker.pisces.context.LoginContext;
import com.basker.pisces.context.LoginContextHolder;
import com.basker.pisces.oss.model.ObjectMeta;
import com.basker.pisces.oss.service.OSSService;
import com.basker.pisces.service.annotation.IgnoreLoginContext;

/**
 * @author hangwen
 * @date 2020/12/12
 */
@RestController
@RequestMapping("/oss")
public class OSSRestController {

    @Autowired
    private OSSService ossService;

    @IgnoreLoginContext
    @GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public Resource download(@RequestParam("path") String path) {
        if (StringUtils.isEmpty(path)) {
            new ByteArrayResource("path is missing".getBytes(StandardCharsets.UTF_8));
        }

        Resource resource = this.ossService.getResource(path);
        if (resource == null) {
            new ByteArrayResource("path is not found".getBytes(StandardCharsets.UTF_8));
        }

        return resource;
    }

    //    @IgnoreLoginContext
//    @PostMapping("/meta")
//    public ObjectMeta meta(@RequestParam("path") String path) {
//        if (StringUtils.isEmpty(path)) {
//            return ObjectMeta.EMPTY;
//        }
//
//        ObjectMeta meta = this.ossService.getMeta(path);
//        return meta != null ? meta : ObjectMeta.EMPTY;
//    }

    @GetMapping("/status")
    @IgnoreLoginContext
    public String ossOk() {
        return "oss is ok";
    }

    @PostMapping("/upload")
    @IgnoreLoginContext
    public ObjectMeta upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ObjectMeta.EMPTY;
        }

        return this.ossService.upload(this.getContainer(), file.getOriginalFilename(), file.getBytes());
    }

    private String getContainer() {
        LoginContext loginContext = LoginContextHolder.getLoginContext();
        return loginContext != null ?
                DigestUtils.md5DigestAsHex(Objects.toString(loginContext.getUserId()).getBytes(StandardCharsets.UTF_8))
                : null;
    }
}
